import React from 'react';
import ReactDom from 'react-dom';



/*
*   高阶组件可以实现逻辑复用
*   hooks却比高阶组件优雅的多
* */


//co从localStorage中加载数据，localStorage.getItem('uaername') :

//高阶函数
function LoadFromLocal(LoadFromAjaxUserName, name) {
    return class extends React.Component {
        state = {value: null};

        componentDidMount() {
            let value = localStorage.getItem(name)
            this.setState({value: value})
        }

        render() {
            return (
                <LoadFromAjaxUserName value={this.state.value}/>
            );
        }

    }
}

//

function LoadFromAjax(LoadFromUserName) {
    return class extends React.Component {
        state = {value: null};

        componentDidMount() {
            // let value = this.props.value;
            fetch('/translation.json').then(res => res.json()).then(data => {
                // {"tom": "汤姆","jerry": "杰瑞"}
                console.log('this.props.value', this.props.value);
                this.setState({value: data[this.props.value]})   //   取key对应的value,接收的属性为英文名，调用远程服务接口，转换成对应的中文名，赋值给state的value
            });
        }

        render() {
            console.log(this.state.value)

            return (
                <LoadFromUserName value={this.state.value}/>
            );
        }

    }
}

//1   包装礼物（从里往外）
const UserName = (props) => {
    return <input defaultValue={props.value}/>
}
//2
const LoadFromAjaxUserName = LoadFromAjax(UserName);

//3
//把函数组件UserName作为参数传给LoadFromLocal，返回一个新的类组件：
let LoadFromUserName = LoadFromLocal(LoadFromAjaxUserName, 'username');


ReactDom.render(<div><LoadFromUserName/></div>, document.getElementById('root'));


